<template>
	<div class="home" style="display: flex; height: 100vh">
		<Aside
			:is-collapse="isCollapse"
			:routers="routers"
			:menu-title="menuTitle"
			:background-color="backgroundColor"
			@click-menu="clickMenu"
		></Aside>
		<div style="flex: auto">
			<Header
				style="height: 50px"
				@click-collapse="clickMenuCollapse"
				@logout="logout"
			></Header>
			<Main></Main>
		</div>
	</div>
</template>

<script>
import Main from "@/components/home/Main.vue"
import Header from "@/components/home/Header.vue"
import Aside from "@/components/home/Aside.vue"
import { mapState } from "vuex"
import { TagCurMenu } from "@/utils/index.js"
import { submitLogout } from "@/api/login"
import { getUserInfo } from "@/api/user-profile"

export default {
	name: "FrontAdminHome",
	components: {
		Aside,
		Header,
		Main,
	},
	data() {
		return {
			menuTitle: {
				label: "农产品供销管理系统",
				imgUrl: require("@/static/imgs/home/logo.png"),
			},
			isCollapse: false,
			color: "#ffffff",
		}
	},
	computed: {
		...mapState({
			menus: (state) => (state.user ? state.user.menus : []),
			backgroundColor: (state) => state.globalSet.naviColor,
		}),
		routers() {
			return this.handlerMenus(this.menus)
		},
		getTagList() {
			return this.$store.state.tagList
		},
	},
	mounted() {
		this.checkLoginUserStatus()
	},
	created() {
		this.getLoginUser()
	},

	methods: {
		async getLoginUser() {
			let user = this.$store.state.user
			if (!user) {
				let res = await getUserInfo()
				if (res.code == 200) {
					this.$store.commit("changeUser", res.data)
				}
			}
		},

		checkLoginUserStatus() {
			let token = this.$store.state.token
			if (!token) {
				this.$message.error("用户登录过期或会话状态失效")
				setTimeout(() => {
					this.$router.push("/login")
				}, 1000)
			}
		},
		clickMenuCollapse(val) {
			this.isCollapse = val
		},
		clickMenu(item) {
			this.updateTagCurMenu(this, item)
		},
		logout(val) {
			if (val) {
				this.confirm(this.$confirm, "您是否确认退出账户?", async () => {
					let res = await submitLogout()
					if (res.code == 200) {
						this.$Tool.removeStorage("token")
						this.$router.push("/login")
					}
				})
			}
		},

		handlerMenus(menus) {
			let routes = []
			for (let i = 0; i < menus.length; i++) {
				const menu = menus[i]
				let route = {
					label: menu.menuName,
					path: menu.menuPath,
					icon: menu.menuIcon,
					children: [],
				}
				routes.push(route)

				if (menu.children && menu.children.length > 0) {
					route.children = this.handlerMenus(menu.children, [])
				}
			}
			return routes
		},
		updateTagCurMenu: TagCurMenu.updateTagCurMenu,
	},
}
</script>

<style scoped></style>
